// ignore_for_file: use_build_context_synchronously

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:flutter_house_manager/utils/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key, this.toName});

  /// 登录后跳转的子级页面路径 有可能有 也有可能没有
  final String? toName;

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  int _count = 60;
  Timer? _timer;
  bool _isSend = false;

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  /// 倒计时
  _getCountDown() async {
    // 1. 判断是否已经发送验证码
    if (_isSend) {
      return;
    }

    // 2. 获取手机号码
    String phone = _phoneController.text;
    // 2.1 判断手机号码是否为空
    if (phone.isEmpty) {
      PromptAction.showWarning('请输入手机号码');
      return;
    }
    // 2.2 验证手机号码 /^1[3-9]\d{9}$/
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
      PromptAction.showWarning('请输入正确的手机号码');
      return;
    }

    // 3. 发送验证码
    final res = await sendCodeAPI({"mobile": phone});
    Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        _codeController.text = res["code"] ?? "";
      });
    });

    // 4. 启动倒计时
    if (_count == 60) {
      _isSend = true;
      // 1. 开启倒计时
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        // 1.1 判断
        if (_count == 0) {
          // 1.1.1 关闭倒计时
          _timer?.cancel();
          _isSend = false;
          _count = 60;
          setState(() {});
          return;
        }
        // 1.2 刷新页面
        setState(() {
          _count--;
        });
      });
    } else {
      PromptAction.showWarning('请1分钟后再获取');
    }
  }

  /// 展示倒计时
  showCountText() {
    if (_isSend) {
      return Text(
        '$_count s后重新获取',
        style: const TextStyle(color: Colors.grey),
      );
    } else {
      return const Text(
        '获取验证码',
        style: TextStyle(
          color: Color.fromARGB(255, 85, 145, 175),
        ),
      );
    }
  }

  /// 登录
  login() async {
    // 1. 校验
    String phone = _phoneController.text;
    String code = _codeController.text;
    // 1.1 判断手机号码是否为空
    if (phone.isEmpty) {
      PromptAction.showWarning('请输入手机号码');
      return;
    }
    // 1.2 验证手机号码 /^1[3-9]\d{9}$/
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
      PromptAction.showWarning('请输入正确的手机号码');
      return;
    }
    // 1.3 判断验证码是否为空
    if (code.isEmpty) {
      PromptAction.showWarning('请输入验证码');
      return;
    }
    if (!RegExp(r'^\d{6}$').hasMatch(code)) {
      PromptAction.showWarning('请输入6位的验证码');
      return;
    }
    // 2. 调用接口获取token
    final res = await loginAPI({"mobile": phone, "code": code});
    // 3. 存储token
    await tokenManager.setToken(res["token"] ?? "",
        refreshToken: res["refreshToken"] ?? "");
    PromptAction.showSuccess('登录成功');

    // 5. 发出登录成功的事件通知
    eventBus.fire(LoginSuccessEvent());

    // 6. 判断是否有回调页面，如果有就跳转
    if (widget.toName != null) {
      Navigator.popAndPushNamed(context, widget.toName!);
      // print('${widget.toName}111');
      return;
    }

    // 4. 返回上一页
    // Navigator.pop(context);
    Navigator.of(context).pushNamed('/');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      icon: Icon(Icons.phone),
                      iconColor: Color.fromARGB(255, 85, 145, 175),
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _getCountDown();
                  },
                  child: showCountText(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                icon: Icon(Icons.lock),
                iconColor: Color.fromARGB(255, 85, 145, 175),
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _timer = null;
  }
}
